package com.skaz.util;

import com.skaz.Constants;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.MalformedJwtException;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.SignatureException;
import io.jsonwebtoken.UnsupportedJwtException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;

/**
 * @Author: jungle
 * @Date: 2018/11/8 11:33 AM
 */
public class Jwts {
    public static final String secretKey = Constants.SECURITY_SECRET;
    private static final Logger logger = LoggerFactory.getLogger(Jwts.class);

    public static String createToken(String userName) {
        JwtBuilder jwt = io.jsonwebtoken.Jwts.builder();
        jwt.setSubject(userName);
        jwt.setIssuedAt(new Date());
        jwt.signWith(SignatureAlgorithm.HS512, secretKey);
        return jwt.compact();
    }

    public static String getSubject(String token) {
        return getClaims(token).getSubject();
    }

    public static Claims getClaims(String accessToken) {
        return io.jsonwebtoken.Jwts.parser().setSigningKey(secretKey).parseClaimsJws(accessToken).getBody();
    }

    public static boolean validateToken(String token) {
        try {
            io.jsonwebtoken.Jwts.parser().setSigningKey(secretKey).parseClaimsJws(token);
            return true;
        } catch (SignatureException e) {
            logger.info("Invalid JWT signature.");
            logger.trace("Invalid JWT signature trace: {}", e);
        } catch (MalformedJwtException e) {
            logger.info("Invalid JWT token.");
            logger.trace("Invalid JWT token trace: {}", e);
        } catch (ExpiredJwtException e) {
            logger.info("Expired JWT token.");
            logger.trace("Expired JWT token trace: {}", e);
        } catch (UnsupportedJwtException e) {
            logger.info("Unsupported JWT token.");
            logger.trace("Unsupported JWT token trace: {}", e);
        } catch (IllegalArgumentException e) {
            logger.info("JWT token compact of handler are invalid.");
            logger.trace("JWT token compact of handler are invalid trace: {}", e);
        }
        return false;
    }
}
